package com.congee02.modelshellmvn.service;

import com.congee02.modelshellmvn.anno.NeedPermission;
import com.congee02.modelshellmvn.anno.NeedSave;
import com.congee02.modelshellmvn.entity.account.Account;
import com.congee02.modelshellmvn.entity.account.AccountRoleDefinition;
import com.congee02.modelshellmvn.exception.AccountMissingException;
import com.congee02.modelshellmvn.exception.AlterRoleMissingException;
import com.congee02.modelshellmvn.repo.account.AccountRepository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.Optional;

@Service
public class SysadminService {

    @Resource
    private AccountRepository accountRepository;

    @NeedPermission(value = AccountRoleDefinition.SYS_ADMIN)
    @NeedSave(repo = AccountRepository.class)
    @Transactional
    public Account alterRole4Account(Account account) {

        Long id = account.getId();
        Integer role = account.getRole();

        if (id == null) {
            throw new AccountMissingException();
        }

        if (role == null) {
            throw new AlterRoleMissingException();
        }

        Optional<Account> found = accountRepository.findById(id);
        if (! found.isPresent()) {
            throw new AccountMissingException();
        }

        Account update = found.get();
        return update.setRole(account.getRole());
    }

}
